package com.luo.wheresmytakeaway.filter;


import com.alibaba.fastjson2.JSONObject;
import com.luo.wheresmytakeaway.pojo.Results;
import com.luo.wheresmytakeaway.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Slf4j
@Component
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("初始化LoginFilter");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = request.getRequestURI();
        if (url.contains("login")) {
            log.info("登录放行");
            filterChain.doFilter(request, response);
            return;
        }
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String jwt = authHeader.substring(7); // 去掉 Bearer 前缀
            log.info("获取请求头token:{}", jwt);
            if (!StringUtils.hasLength(jwt)) {
                log.info("请求头token为空");
                Results error = Results.error("NOT_LOGIN");
                String notLogin = JSONObject.toJSONString(error);
                response.getWriter().write(notLogin);
                return;
            }
            try {
                JwtUtils.parseJWT(jwt);
            } catch (Exception e) {
                log.info("解析jwt失败");
                Results error = Results.error("NOT_LOGIN");
                String notLogin = JSONObject.toJSONString(error);
                response.getWriter().write(notLogin);
                return;
            }
        }
        log.info("令牌合法放行");
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        log.info("销毁LoginFilter");
    }
}
